package com.person.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.person.common.CommonResult;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class ProviderService {
    /**
     * 正常访问的       方法master
     *
     * @param id
     * @return
     */
    public CommonResult paymentInfo_ok(Integer id) {
        return CommonResult.ok(200, "success",
                "线程池" + Thread.currentThread().getName() + "payment" + id + "\t" + "O(∩_∩)O哈哈~");
    }

    @HystrixCommand(fallbackMethod = "paymentInfo_timeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public CommonResult paymentInfo_timeout(Integer id) {
        int timeOut = 3;
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return CommonResult.ok(200, "success",
                "线程池" + Thread.currentThread().getName() + "payment" + id + "\t" + "O(∩_∩)O哈哈~ 耗时(秒):" + timeOut);
    }


    public CommonResult paymentInfo_timeoutHandler(Integer id) {
        return CommonResult.error("error",
                "8001系统繁忙或出错请稍后重试" + "\t" + "o(╥﹏╥)o");
    }

    //服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerHandler", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),//失败率多少后跳闸
    })
    public CommonResult paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("********id 不能为负数");
        }
        String serimple = IdUtil.simpleUUID();
        return CommonResult.ok(200, "success", Thread.currentThread().getName() + "\t" + "调用成功,流水号:" + serimple);
    }

    public CommonResult paymentCircuitBreakerHandler(@PathVariable("id") Integer id) {
        return CommonResult.error("error", "8001崩溃了o(╥﹏╥)o..." + "\t" + "小哥哥正在抢修请耐心等待(*^▽^*)...");
    }
}
